#Boa:Dialog:Dialog1

import wx
import utiles
import consultasBD

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2, wxID_DIALOG1BUTTON4, 
 wxID_DIALOG1LISTBOX1, wxID_DIALOG1PANEL1, wxID_DIALOG1STATICTEXT1, 
 wxID_DIALOG1STATICTEXT2, wxID_DIALOG1TEXTCTRL1, wxID_DIALOG1TEXTCTRL2, 
] = [wx.NewId() for _init_ctrls in range(10)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(377, 65), size=wx.Size(555, 502), style=wx.CLOSE_BOX,
              title='Busqueda de producto por descripcion')
        self.SetClientSize(wx.Size(547, 475))

        self.panel1 = wx.Panel(id=wxID_DIALOG1PANEL1, name='panel1',
              parent=self, pos=wx.Point(0, 0), size=wx.Size(784, 472),
              style=wx.TAB_TRAVERSAL)

        self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
              label='Descripci\xf3nn', name='staticText1', parent=self.panel1,
              pos=wx.Point(16, 8), size=wx.Size(54, 13), style=0)

        self.textCtrl1 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL1, name='textCtrl1',
              parent=self.panel1, pos=wx.Point(16, 24), size=wx.Size(296, 24),
              style=0, value='')
        self.textCtrl1.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL,
              False, 'Tahoma'))

        self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
              label='Proveedor', name='staticText2', parent=self.panel1,
              pos=wx.Point(320, 8), size=wx.Size(50, 13), style=0)

        self.textCtrl2 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL2, name='textCtrl2',
              parent=self.panel1, pos=wx.Point(320, 24), size=wx.Size(216, 24),
              style=0, value='')
        self.textCtrl2.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL,
              False, 'Tahoma'))

        self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label='Buscar',
              name='button1', parent=self.panel1, pos=wx.Point(16, 432),
              size=wx.Size(96, 32), style=0)
        self.button1.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              'Tahoma'))
        self.button1.Bind(wx.EVT_BUTTON, self.OnButtonBuscar,
              id=wxID_DIALOG1BUTTON1)

        self.button4 = wx.Button(id=wxID_DIALOG1BUTTON4, label='Cancelar',
              name='button4', parent=self.panel1, pos=wx.Point(120, 432),
              size=wx.Size(96, 32), style=0)
        self.button4.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              'Tahoma'))
        self.button4.Bind(wx.EVT_BUTTON, self.OnButtonCancelar,
              id=wxID_DIALOG1BUTTON4)

        self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2, label='Salir',
              name='button2', parent=self.panel1, pos=wx.Point(440, 432),
              size=wx.Size(96, 32), style=0)
        self.button2.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              'Tahoma'))
        self.button2.Bind(wx.EVT_BUTTON, self.OnButtonSalir,
              id=wxID_DIALOG1BUTTON2)

        self.listBox1 = wx.ListBox(choices=[], id=wxID_DIALOG1LISTBOX1,
              name='listBox1', parent=self.panel1, pos=wx.Point(16, 56),
              size=wx.Size(520, 368), style=0)
        self.listBox1.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False,
              'Tahoma'))
        self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBoxEvento,
              id=wxID_DIALOG1LISTBOX1)

    def __init__(self, parent, valor):
        self._init_ctrls(parent)
        self.codigo = ""
        self.descripcion = ""
        self.conectado = None
        self.valor = valor
        self.textCtrl1.SetValue(valor)
        if valor != "":
            self.button1.SetFocus()
            self.OnButtonBuscar(None)
        
    def OnButtonSalir(self, event):
        self.Close()

    def OnButtonBuscar(self, event):
        if self.textCtrl1.GetValue() == "" and self.textCtrl2.GetValue() == "":
            texto1 = "             Debe especificar descripci\xf3n\n"
            texto2 = "                o nombre del proveedor."
            texto = texto1 + texto2
            utiles.mensaje(None, texto)
            return 1
        cadena1 = self.textCtrl1.GetValue()
        cadena2 = self.textCtrl2.GetValue()
        
        #con descripcion y sin proveedor
        aux1 = []
        aux1.append("SELECT pr.cod AS cod, pr.des AS des, pr.pre AS pre,")
        aux1.append("       c.nombre AS nombre ")
        aux1.append("FROM ")
        aux1.append("   (SELECT p.codsussan AS cod, p.descri AS des, ")
        aux1.append("           p.preciolt1 AS pre, p.proveedor AS idprov")
        aux1.append("      FROM productos AS p ")
        aux1.append("      WHERE p.descri LIKE '%"+cadena1+"%') as pr,")
        aux1.append("   proveedor AS c ")
        aux1.append("WHERE idprov = c.idproveedor ORDER BY nombre, cod")

        #sin descripcion y con proveedor
        aux2 = []
        aux2.append("SELECT p.codsussan AS cod, p.descri AS des,")
        aux2.append("    p.preciolt1 AS pre, pr.nombre AS nombre ")
        aux2.append("FROM productos AS p, ")
        aux2.append("   (SELECT idproveedor, nombre FROM proveedor ")
        aux2.append("    WHERE nombre LIKE '%"+cadena2+"%') as pr ")
        aux2.append("WHERE p.proveedor = pr.idproveedor ORDER BY nombre, cod")

        #con descripcion y con proveedor
        aux3 = []
        aux3.append("SELECT c.cod, c.des, c.pre, c.nombre ")
        aux3.append("FROM ")
        aux3.append("   (SELECT pr.cod, pr.des, pr.pre, pv.nombre ")
        aux3.append("     FROM ")
        aux3.append("        (SELECT p.codsussan AS cod, p.descri AS des, ")
        aux3.append("                p.preciolt1 AS pre, p.proveedor AS idprov")
        aux3.append("          FROM productos AS p ")
        aux3.append("          WHERE p.descri LIKE '%"+cadena1+"%') as pr,")
        aux3.append("        proveedor as pv")
        aux3.append("     WHERE pv.idproveedor = pr.idprov) AS c ")
        aux3.append("WHERE c.nombre LIKE '%"+cadena2+"%' ORDER BY nombre, cod")

        #sin descripcion ni proveedor => no se procesa
        #porque equivale a mostrar toda la tabla

        #creando la consultaSQL segun valores de busqueda introducidos
        if cadena1 != "" and cadena2 != "":
            consultaSQL = ""
            for elemento in aux3:
                consultaSQL = consultaSQL + elemento
        elif cadena1 == "":
            consultaSQL = ""
            for elemento in aux2:
                consultaSQL = consultaSQL + elemento
        else:
            consultaSQL = ""
            for elemento in aux1:
                consultaSQL = consultaSQL + elemento
        self.llenarListBox(consultaSQL)    
        
    def llenarListBox(self, consultaSQL):
        print "SELECT -> obteniendo informacion de productos y proveedores"
        datos, self.conectado = consultasBD.ordenCrudaDict(consultaSQL, self.conectado)
        if len(datos) == 0:
            texto = "No hay productos con los criterios ingresados"
            utiles.mensaje(None, texto)
            self.textCtrl1.SetFocus()
            return 1
        print "SELECT -> procesando"
        sp = "  -  "
        for item in datos:
            linea = item['cod']+sp+item['des']+sp+'$'+str(item['pre'])+sp+item['nombre']
            self.listBox1.Append(linea)
        self.listBox1.Select(0)
        self.listBox1.SetFocus()
        self.textCtrl1.Enable(False)
        self.textCtrl2.Enable(False) 
        self.button1.Enable(False) #buscar
        self.button2.SetLabel("Aceptar")
        self.OnListBoxEvento(None)

    def OnButtonCancelar(self, event):
        self.textCtrl1.Enable(True)
        self.textCtrl1.SetValue("")
        self.textCtrl2.Enable(True)
        self.textCtrl2.SetValue("")
        self.button1.Enable(True) #buscar
        self.button2.SetLabel("Salir")
        self.listBox1.Clear()
        self.textCtrl1.SetFocus()
        self.codigo = ""
        self.descripcion = ""

    def OnListBoxEvento(self, event):
        aux = self.listBox1.GetItems()
        producto = aux[self.listBox1.GetSelection()]
        self.codigo, self.descripcion, precio, proveedor = producto.split("  -  ")
